package cn.edu.njuit.webserver.securityserver.security;

import cn.edu.njuit.webserver.securityserver.filter.JwtApiFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.bind.annotation.PutMapping;

/**
 * @Description: TODO
 * @Data: 2022/9/5 22:09
 * @Author: guzy
 */
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        /**
         * 指定密码加密模式：加盐哈希加密
         */
        return new BCryptPasswordEncoder();
    }

    @Autowired
    JwtApiFilter jwtApiFilter;

    public void configure(HttpSecurity httpSecurity) throws Exception {
        //设置⽆状态的会话
        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                //⽆状态请求模式下，不需要拦截跨域脚本攻击
                .and().csrf().disable()
                //配置权限控制策略
                .authorizeRequests()
                //放行的api
                .antMatchers("/api/hello").hasAuthority("role_admin")
                .antMatchers("/api/login").permitAll()
                .antMatchers("/api/regist").permitAll()
                .antMatchers("/api/send-sms").permitAll()
                .antMatchers("/api/sms-login").permitAll()
                .antMatchers("/api/wechatlogin").permitAll()
//                //订单接口
                .antMatchers("/api/orders/**").permitAll()
                //拦截的api
//                .antMatchers("/api/sys/**").authenticated()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(jwtApiFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
